﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Data.Model;
using NHibernate;
using Senparc.Weixin.MP.Entities;
using NHibernate.Criterion;
using System.Collections.Generic;
using ZLCMS.Business.Util;
using Senparc.Weixin.MP.Helpers;
using DotNet.Common.NHibernateUtil;
using Newtonsoft.Json;
using ZLCMS.Business.WeixinService.Data;

namespace ZLCMS.Web.SystemManage.Weixin
{
    public partial class EditApply : System.Web.UI.Page
    {
        protected FrameHelper _frameHelper;

        protected WxApplyConfig _applyDb;

        private string _uid;

        protected string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            _frameHelper = new FrameHelper(this);

            //初始化全局变量值
            InitializeGlobalValue();
            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                Save();
            }
        }

        #region 保存操作(新建/更新) + private void Save()
        /// <summary>
        /// 保存操作
        /// </summary>
        private void Save()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                try
                {
                    if (string.IsNullOrEmpty(_uid))//新建
                    {
                        _applyDb = new WxApplyConfig();

                        _applyDb.Title = tb_name.Text;
                        _applyDb.Description = tb_desc.Text;
                        _applyDb.Content = txtContent.Value;

                        _applyDb.BeginDate = DateTime.Parse(tb_sdate.Text);

                        _applyDb.EndDate = DateTime.Parse(tb_edate.Text + " 23:59:59");

                        _applyDb.CreateDate = DateTime.Now;

                        CreateItemData(_applyDb);

                        _applyDb.Status = "SETTING";
                        _applyDb.OwnerAccount = _userAccount;
                        _applyDb.SuccessNotice = tb_success.Text;
                        _applyDb.EndNotice = tb_end.Text;
                        _applyDb.VoteOpenUrl = fc_open.Value;

                        //session.Update(_applyDb);
                    }
                    else//修改
                    {
                        _applyDb.Title = tb_name.Text;
                        _applyDb.Description = tb_desc.Text;
                        _applyDb.Content = txtContent.Value;

                        _applyDb.BeginDate = DateTime.Parse(tb_sdate.Text);
                        _applyDb.EndDate = DateTime.Parse(tb_edate.Text);
                        _applyDb.CreateDate = DateTime.Now;

                        CreateItemData(_applyDb);

                        _applyDb.OwnerAccount = _userAccount;
                        _applyDb.SuccessNotice = tb_success.Text;
                        _applyDb.EndNotice = tb_end.Text;
                        _applyDb.VoteOpenUrl = fc_open.Value;

                        //session.Update(_applyDb);
                    }

                    WxMaterial mat = session.Get<WxMaterial>(_applyDb.MaterialId);
                    if (mat == null)
                    {
                        mat = new WxMaterial();
                        mat.CreateDate = DateTime.Now;
                    }
                    mat.MsgType = "apply";
                    mat.OwnerAccount = _userAccount;
                    mat.Status = "1";
                    mat.Title = _applyDb.Title;
                    mat.UpdateDate = DateTime.Now;
                    session.SaveOrUpdate(mat);

                    WxMaterialNews news = session.CreateQuery("from WxMaterialNews where MaterialId=:mid").SetParameter("mid", mat.Id)
                        .UniqueResult<WxMaterialNews>();
                    if (news == null)
                    {
                        news = new WxMaterialNews();
                    }
                    news.Content = _applyDb.Content;
                    news.ContentType = "URL";
                    news.Description = _applyDb.Description;
                    news.MaterialId = mat.Id;
                    news.OwnerAccount = _userAccount;
                    news.Title = _applyDb.Title;
                    session.SaveOrUpdate(news);

                    _applyDb.MaterialId = mat.Id;
                    session.SaveOrUpdate(_applyDb);

                    session.Flush();
                }
                catch (System.Exception ex)
                {
                    _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }

            _frameHelper.Alert(new ReturnCode()
            {
                statusCode = 200,
                message = "操作成功!",
                callbackType = "closeCurrent",
                navTabId = _frameHelper.NavTabId
            });
        }
        #endregion

        private void CreateItemData(WxApplyConfig configDb)
        {
            configDb.ApplyItem1 = JsonConvert.SerializeObject(
                new WxApplyConfigItem()
                {
                    IsAvailable = ipc_i1.Checked ? "1" : "0",
                    Title = tb_item_1.Text,
                    Type = ddl_item_1.SelectedValue,
                    IsRequired = cb_m_1.Checked ? "1" : "0",
                    OptionalData = ipc_i1.Checked ? tb_val_1.Text : ""
                });
            configDb.ApplyItem2 = JsonConvert.SerializeObject(
                new WxApplyConfigItem()
                {
                    IsAvailable = ipc_i2.Checked ? "1" : "0",
                    Title = tb_item_2.Text,
                    Type = ddl_item_2.SelectedValue,
                    IsRequired = cb_m_2.Checked ? "1" : "0",
                    OptionalData = ipc_i2.Checked ? tb_val_2.Text : ""
                });
            configDb.ApplyItem3 = JsonConvert.SerializeObject(
                new WxApplyConfigItem()
                {
                    IsAvailable = ipc_i3.Checked ? "1" : "0",
                    Title = tb_item_3.Text,
                    Type = ddl_item_3.SelectedValue,
                    IsRequired = cb_m_3.Checked ? "1" : "0",
                    OptionalData = ipc_i3.Checked ? tb_val_3.Text : ""
                });
            configDb.ApplyItem4 = JsonConvert.SerializeObject(
                new WxApplyConfigItem()
                {
                    IsAvailable = ipc_i4.Checked ? "1" : "0",
                    Title = tb_item_4.Text,
                    Type = ddl_item_4.SelectedValue,
                    IsRequired = cb_m_4.Checked ? "1" : "0",
                    OptionalData = ipc_i4.Checked ? tb_val_4.Text : ""
                });
            configDb.ApplyItem5 = JsonConvert.SerializeObject(
                new WxApplyConfigItem()
                {
                    IsAvailable = ipc_i5.Checked ? "1" : "0",
                    Title = tb_item_5.Text,
                    Type = ddl_item_5.SelectedValue,
                    IsRequired = cb_m_5.Checked ? "1" : "0",
                    OptionalData = ipc_i5.Checked ? tb_val_5.Text : ""
                });
            configDb.ApplyItem6 = JsonConvert.SerializeObject(
                new WxApplyConfigItem()
                {
                    IsAvailable = ipc_i6.Checked ? "1" : "0",
                    Title = tb_item_6.Text,
                    Type = ddl_item_6.SelectedValue,
                    IsRequired = cb_m_6.Checked ? "1" : "0",
                    OptionalData = ipc_i6.Checked ? tb_val_6.Text : ""
                });
            configDb.ApplyItem7 = JsonConvert.SerializeObject(
                new WxApplyConfigItem()
                {
                    IsAvailable = ipc_i7.Checked ? "1" : "0",
                    Title = tb_item_7.Text,
                    Type = ddl_item_7.SelectedValue,
                    IsRequired = cb_m_7.Checked ? "1" : "0",
                    OptionalData = ipc_i7.Checked ? tb_val_7.Text : ""
                });
            configDb.ApplyItem8 = JsonConvert.SerializeObject(
                new WxApplyConfigItem()
                {
                    IsAvailable = ipc_i8.Checked ? "1" : "0",
                    Title = tb_item_8.Text,
                    Type = ddl_item_8.SelectedValue,
                    IsRequired = cb_m_8.Checked ? "1" : "0",
                    OptionalData = ipc_i8.Checked ? tb_val_8.Text : ""
                });
            configDb.ApplyItem9 = JsonConvert.SerializeObject(
                new WxApplyConfigItem()
                {
                    IsAvailable = ipc_i9.Checked ? "1" : "0",
                    Title = tb_item_9.Text,
                    Type = ddl_item_9.SelectedValue,
                    IsRequired = cb_m_9.Checked ? "1" : "0",
                    OptionalData = ipc_i9.Checked ? tb_val_9.Text : ""
                });
            configDb.ApplyItem10 = JsonConvert.SerializeObject(
                new WxApplyConfigItem()
                {
                    IsAvailable = ipc_i10.Checked ? "1" : "0",
                    Title = tb_item_10.Text,
                    Type = ddl_item_10.SelectedValue,
                    IsRequired = cb_m_10.Checked ? "1" : "0",
                    OptionalData = ipc_i10.Checked ? tb_val_10.Text : ""
                });

            _applyDb.IsSendEmail = cb_mail.Checked ? "1" : "0";
            _applyDb.EmailAddr = tb_mail.Text;
        }

        #region 初始化全局变量 + protected void InitializeGlobalValue()
        /// <summary>
        /// 初始化全局变量
        /// </summary>
        protected void InitializeGlobalValue()
        {
            if (!IsPostBack)
            {
                ViewState["uid"] = Request["uid"];
            }
            _uid = (string)ViewState["uid"];

            if (!string.IsNullOrEmpty(_uid))
            {
                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    try
                    {
                        _applyDb = session.CreateCriteria<WxApplyConfig>().Add(Expression.Eq("Id", int.Parse(_uid))).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxApplyConfig>();

                        if (_applyDb == null)
                        {
                            throw new Exception("找不到对应信息.");
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                        return;
                    }
                }
            }
        }
        #endregion

        #region 初始化控件值 + protected void InitializeContent()
        /// <summary>
        /// 初始化控件值
        /// </summary>
        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                BindItemType(ddl_item_1);
                BindItemType(ddl_item_2);
                BindItemType(ddl_item_3);
                BindItemType(ddl_item_4);
                BindItemType(ddl_item_5);
                BindItemType(ddl_item_6);
                BindItemType(ddl_item_7);
                BindItemType(ddl_item_8);
                BindItemType(ddl_item_9);
                BindItemType(ddl_item_10);

                if (!string.IsNullOrEmpty(_uid))
                {
                    tb_name.Text = _applyDb.Title;
                    tb_desc.Text = _applyDb.Description;
                    txtContent.Value = _applyDb.Content;

                    tb_sdate.Text = _applyDb.BeginDate.ToString("yyyy-MM-dd");
                    tb_edate.Text = _applyDb.EndDate.ToString("yyyy-MM-dd");

                    WxApplyConfigItem item;
                    item = JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem1 == null ? "" : _applyDb.ApplyItem1);
                    if (item != null)
                    {
                        ipc_i1.Checked = item.IsAvailable == "1" ? true : false;
                        tb_item_1.Text = item.Title;
                        ddl_item_1.SelectedValue = item.Type;
                        cb_m_1.Checked = item.IsRequired == "1" ? true : false;
                        tb_val_1.Text = item.OptionalData;
                    }

                    item = JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem2 == null ? "" : _applyDb.ApplyItem2);
                    if (item != null)
                    {
                        ipc_i2.Checked = item.IsAvailable == "1" ? true : false;
                        tb_item_2.Text = item.Title;
                        ddl_item_2.SelectedValue = item.Type;
                        cb_m_2.Checked = item.IsRequired == "1" ? true : false;
                        tb_val_2.Text = item.OptionalData;
                    }

                    item = JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem3 == null ? "" : _applyDb.ApplyItem3);
                    if (item != null)
                    {
                        ipc_i3.Checked = item.IsAvailable == "1" ? true : false;
                        tb_item_3.Text = item.Title;
                        ddl_item_3.SelectedValue = item.Type;
                        cb_m_3.Checked = item.IsRequired == "1" ? true : false;
                        tb_val_3.Text = item.OptionalData;
                    }

                    item = JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem4 == null ? "" : _applyDb.ApplyItem4);
                    if (item != null)
                    {
                        ipc_i4.Checked = item.IsAvailable == "1" ? true : false;
                        tb_item_4.Text = item.Title;
                        ddl_item_4.SelectedValue = item.Type;
                        cb_m_4.Checked = item.IsRequired == "1" ? true : false;
                        tb_val_4.Text = item.OptionalData;
                    }

                    item = JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem5 == null ? "" : _applyDb.ApplyItem5);
                    if (item != null)
                    {
                        ipc_i5.Checked = item.IsAvailable == "1" ? true : false;
                        tb_item_5.Text = item.Title;
                        ddl_item_5.SelectedValue = item.Type;
                        cb_m_5.Checked = item.IsRequired == "1" ? true : false;
                        tb_val_5.Text = item.OptionalData;
                    }

                    item = JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem6 == null ? "" : _applyDb.ApplyItem6);
                    if (item != null)
                    {
                        ipc_i6.Checked = item.IsAvailable == "1" ? true : false;
                        tb_item_6.Text = item.Title;
                        ddl_item_6.SelectedValue = item.Type;
                        cb_m_6.Checked = item.IsRequired == "1" ? true : false;
                        tb_val_6.Text = item.OptionalData;
                    }

                    item = JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem7 == null ? "" : _applyDb.ApplyItem7);
                    if (item != null)
                    {
                        ipc_i7.Checked = item.IsAvailable == "1" ? true : false;
                        tb_item_7.Text = item.Title;
                        ddl_item_7.SelectedValue = item.Type;
                        cb_m_7.Checked = item.IsRequired == "1" ? true : false;
                        tb_val_7.Text = item.OptionalData;
                    }

                    item = JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem8 == null ? "" : _applyDb.ApplyItem8);
                    if (item != null)
                    {
                        ipc_i8.Checked = item.IsAvailable == "1" ? true : false;
                        tb_item_8.Text = item.Title;
                        ddl_item_8.SelectedValue = item.Type;
                        cb_m_8.Checked = item.IsRequired == "1" ? true : false;
                        tb_val_8.Text = item.OptionalData;
                    }

                    item = JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem9 == null ? "" : _applyDb.ApplyItem9);
                    if (item != null)
                    {
                        ipc_i9.Checked = item.IsAvailable == "1" ? true : false;
                        tb_item_9.Text = item.Title;
                        ddl_item_9.SelectedValue = item.Type;
                        cb_m_9.Checked = item.IsRequired == "1" ? true : false;
                        tb_val_9.Text = item.OptionalData;
                    }

                    item = JsonConvert.DeserializeObject<WxApplyConfigItem>(_applyDb.ApplyItem10 == null ? "" : _applyDb.ApplyItem10);
                    if (item != null)
                    {
                        ipc_i10.Checked = item.IsAvailable == "1" ? true : false;
                        tb_item_10.Text = item.Title;
                        ddl_item_10.SelectedValue = item.Type;
                        cb_m_10.Checked = item.IsRequired == "1" ? true : false;
                        tb_val_10.Text = item.OptionalData;
                    }

                    tb_success.Text = _applyDb.SuccessNotice;
                    tb_end.Text = _applyDb.EndNotice;

                    fc_open.Value = _applyDb.VoteOpenUrl;

                    cb_mail.Checked = _applyDb.IsSendEmail == "1" ? true : false;
                    tb_mail.Text = _applyDb.EmailAddr;
                }
                else
                {
                    tb_name.Text = "预约报名";
                    tb_desc.Text = "亲，请点击进入预约报名页面，感谢您的参与!";
                    txtContent.Value = "亲，请点击进入预约报名页面，感谢您的参与!";

                    tb_sdate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    tb_edate.Text = DateTime.Now.ToString("yyyy-MM-dd");

                    tb_success.Text = "谢谢您，预约报名成功！";
                    tb_end.Text = "亲，预约报名已经结束，请继续关注我们的后续活动哦。";
                }
            }
        #endregion

        }

        private void BindItemType(DropDownList list)
        {
            list.Items.Add(new ListItem() { Text = "文本", Value = "str", Selected = true });
            list.Items.Add(new ListItem() { Text = "多选框", Value = "cbox" });
            list.Items.Add(new ListItem() { Text = "下拉框", Value = "ddlist" });
            list.Items.Add(new ListItem() { Text = "单选框", Value = "rbox" });
            list.Items.Add(new ListItem() { Text = "电话", Value = "phone" });
            list.Items.Add(new ListItem() { Text = "邮箱地址", Value = "email" });
        }
    }
}
